# ========= 导入基础模块 ============
from resources_base.module_base.importbase import *
# ========= 导入数据的类 ============
from trainweb.models import Trainee, Record, RecordDetail, RecordStatus
from basicweb.models import PhaseContent


def index(request):
    """展示培训信息页面"""
    return render(request, 'train/trainee_info.html')


def list_values(request):
    """获取当前产线下所有职位的培训信息"""
    # 获取当前的产线
    line = request.session.get('current_line')
    q_str = request.POST.get('q_str')
    department_id = request.POST.get('department_id')
    status_id = request.POST.get('status_id')
    onboard = 1
    # ====处理状态的查询条件
    status_list = []
    if not status_id:
        status_list = [4, 5, 6, 7, 8]
    elif status_id == '0':
        onboard = 0
        status_list = [4, 5, 6, 7, 8]
    else:
        status_list = [int(status_id)]
    # 获取后端传递的信息
    page = int(request.POST.get('page'))
    limit = int(request.POST.get('limit'))
    # ==== 处理部门的查询条件
    obj_trainees = []
    if not department_id:
        # 获取所有数据
        obj_trainees = list(
            (Trainee.objects.filter(position__department__line_id=line, status_id__in=status_list, onboard=onboard)).filter(
                Q(eid__icontains=q_str) | Q(name__icontains=q_str) | Q(position__department__name__icontains=q_str) | Q(
                    position__name__icontains=q_str)
            ).values(
                'id', 'eid', 'name', 'position__department__line_id', 'position__department__line__name',
                'position__department_id', 'position__department__name', 'position_id', 'position__name', 'status_id'))
    else:
        # 获取所有数据
        obj_trainees = list(
            Trainee.objects.filter(position__department__line_id=line, status_id__in=status_list, onboard=onboard,
                                   position__department_id=department_id).filter(
                Q(eid__icontains=q_str) | Q(name__icontains=q_str) | Q(position__department__name__icontains=q_str) | Q(
                    position__name__icontains=q_str)
            ).values(
                'id', 'eid', 'name', 'position__department__line_id', 'position__department__line__name',
                'position__department_id', 'position__department__name', 'position_id', 'position__name'))

    # 遍历记录：附加上完成的百分比 pass/total
    for index, value in enumerate(obj_trainees):
        # 附加百分比
        obj_trainees[index].update(get_position_complete_percent(value))

    # 分页
    one_page_data = obj_trainees[(page - 1) * limit: page * limit]
    # 返回
    return JsonResponse({'code': 0, 'count': len(obj_trainees), 'data': one_page_data})


def get_position_complete_percent(data):
    """获取当前职位三个阶段的完成比例 --- pass/total"""
    # 定义返回的结果类型
    result = {'phase_one': 0, 'phase_two': 0, 'phase_three': 0, 'phase_one_status': -1, 'phase_two_status': -1,
              'phase_three_status': -1, }
    result_keys = ['phase_one', 'phase_two', 'phase_three']
    result_status_keys = ['phase_one_status', 'phase_two_status', 'phase_three_status']
    # 获取当前员工当前职位的record记录
    obj_records = list(
        Record.objects.filter(trainee__eid=data.get('eid'), trainee__position_id=data.get('position_id')).values())
    # 判断是否为空
    if obj_records:
        # # === 表明有record记录
        for index, value in enumerate(obj_records):
            result[result_keys[index]] = int(value.get('pass_task') * 100 / value.get('total_task'))
            # 判断是否有fail
            if value.get('fail_task') > 0:
                result[result_status_keys[index]] = 1
            else:
                result[result_status_keys[index]] = 0
    # 返回
    return result


def get_current_phase_phasecontent(request):
    """获取当前用户再当前职位上应该录入的阶段和内容"""
    # 获取当前的产线
    line = request.session.get('current_line')
    # 获取前台传递的数据
    employee_id = request.POST.get('employee_id')
    position_id = request.POST.get('position_id')
    # 获取当前职位的阶段的具体内容！！
    position_phasecontent = list(
        PhaseContent.objects.filter(phase__position_id=position_id).values('id', 'name', 'phase_id',
                                                                           'phase__phasename__name'))
    # 判断当前职位是否有阶段内容
    if not position_phasecontent:
        return JsonResponse({'status': False, 'error': "当前的职位没有阶段内容关联！"})

    # 在record【某一个职位的记录概况表】表
    obj_record = Record.objects.filter(trainee__eid=employee_id, trainee__position_id=position_id)
    # 判断
    if not obj_record or obj_record[0].completed_task == 0:
        # 当前的员工的当前职位从来没有录入过数据
        # == 获取当前阶段的第一条记录
        first_record = position_phasecontent[0]
        # 添加阶段下拉框信息
        phase = [{'name': first_record.get('phase__phasename__name'), 'value': first_record.get('phase_id')}]
        # 添加阶段内容的下拉框
        phasecontent = [{'name': first_record.get('name'), 'value': first_record.get('id')}]
        # 返回
        return JsonResponse({'status': True, 'phase': phase, 'phasecontent': phasecontent})

    else:
        # 当前的员工的当前职位已经录入过数据, 自动填充上一个录入内容的下一个内容！
        # 获取最后的记录
        # last_record = obj_record.last()   #   10个  --》position_phasecontent[10]
        # 在recordDetail中取出状态为pass或者fail的数量
        completed_number = RecordDetail.objects.filter(record__trainee__eid=employee_id,
                                                       record__trainee__position_id=position_id,
                                                       status_id__in=[2, 3]).count()
        # 获取下一个任务
        next_phase_phasecontent = position_phasecontent[completed_number]
        # 添加阶段下拉框信息
        phase = [{'name': next_phase_phasecontent.get('phase__phasename__name'),
                  'value': next_phase_phasecontent.get('phase_id')}]
        # 添加阶段内容的下拉框
        phasecontent = [{'name': next_phase_phasecontent.get('name'), 'value': next_phase_phasecontent.get('id')}]
        # 返回
        return JsonResponse({'status': True, 'phase': phase, 'phasecontent': phasecontent})


def add_record_commit(request):
    """记录添加的提交"""
    # 获取前台传递的数据
    rec = request.POST
    # 获取当前用户当前职位的记录 -- 修改状态
    obj_trainee = Trainee.objects.filter(eid=rec.get('eid'), position_id=rec.get('position')).first()

    # 获取当前记录的Record信息 --- Record  -- 判断当前的record记录是否创建
    obj_record = Record.objects.filter(trainee=obj_trainee, phase_id=rec.get('phase'))
    # 判断record是否存在，如果不存在，创建，如果存在，累加
    if not obj_record:
        # record不存在
        try:
            # == 1. 添加record信息 ===
            # 获取total_task
            total_number = PhaseContent.objects.filter(phase_id=rec.get('phase')).count()
            # 添加-- 判断
            if rec.get('status') == "1":  # inTraining
                Record.objects.create(trainee_id=obj_trainee.id, phase_id=rec.get('phase'), total_task=total_number,
                                      completed_task=0, pass_task=0, fail_task=0,
                                      total_training=rec.get('training_time'),
                                      total_working=rec.get('working_time'),
                                      create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            elif rec.get('status') == "2":  # Pass
                Record.objects.create(trainee_id=obj_trainee.id, phase_id=rec.get('phase'), total_task=total_number,
                                      completed_task=1, pass_task=1, fail_task=0,
                                      total_training=rec.get('training_time'),
                                      total_working=rec.get('working_time'),
                                      create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            elif rec.get('status') == "3":  # Fail
                Record.objects.create(trainee_id=obj_trainee.id, phase_id=rec.get('phase'), total_task=total_number,
                                      completed_task=1, pass_task=0, fail_task=1,
                                      total_training=rec.get('training_time'),
                                      total_working=rec.get('working_time'),
                                      create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

            # == 2. 添加RecordDetail
            # 获取刚刚添加的记录 -- 刚查入
            obj_record_last = Record.objects.filter(trainee=obj_trainee, phase_id=rec.get('phase')).first()
            # 添加detail
            RecordDetail.objects.create(record_id=obj_record_last.id, phasecontent_id=rec.get('phasecontent'),
                                        status_id=rec.get('status'),
                                        training_time=rec.get('training_time'), working_time=rec.get('working_time'),
                                        remark="【" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "】--状态：" +
                                               RecordStatus.objects.filter(
                                                   id=rec.get('status')).first().name + "&nbsp&nbsp工时：" + str(
                                            rec.get('training_time'))
                                               + "&nbsp&nbsp培训时长：" + str(rec.get('working_time')) + "&nbsp&nbsp标注："
                                               + rec.get('remark') + "<br>",
                                        record_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

            # == 3. 修改trainee状态
            if obj_trainee.status_id == 4:
                obj_trainee.status_id = 5
                obj_trainee.save()
        except Exception as e:
            return JsonResponse({'status': False, 'error': "提交培训信息出现异常，具体原因：" + str(e)})

        return JsonResponse({'status': True})

    else:
        # record存在，累加pass_task, fail_task, total_training, total_working
        try:
            current_record = obj_record[0]
            # ===1. 累加培训pass_task, fail_task, total_training, total_working ===
            if rec.get('status') == "1":  # inTraining
                # 开始修改
                current_record.total_training += float(rec.get('training_time'))
                current_record.total_working += float(rec.get('working_time'))
            elif rec.get('status') == "2":  # Pass
                current_record.completed_task += 1
                current_record.pass_task += 1
                current_record.total_training += float(rec.get('training_time'))
                current_record.total_working += float(rec.get('working_time'))
            elif rec.get('status') == "3":  # Fail
                current_record.completed_task += 1
                current_record.fail_task += 1
                current_record.total_training += float(rec.get('training_time'))
                current_record.total_working += float(rec.get('working_time'))

            # 写入到数据库！
            current_record.save()

            # === 2. 添加recorddetail ===
            RecordDetail.objects.create(record_id=current_record.id, phasecontent_id=rec.get('phasecontent'),
                                        status_id=rec.get('status'),
                                        training_time=rec.get('training_time'), working_time=rec.get('working_time'),
                                        remark="【" + datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "】--状态：" +
                                               RecordStatus.objects.filter(
                                                   id=rec.get('status')).first().name + "&nbsp&nbsp工时：" + str(
                                            rec.get('training_time'))
                                               + "&nbsp&nbsp培训时长：" + str(rec.get('working_time')) + "&nbsp&nbsp标注："
                                               + rec.get('remark') + "<br>",
                                        record_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            # ===3. 判断当前是否完成！【不是某一个阶段，是三个阶段都完成】 ===
            # 计算三个阶段的任务和
            total_phase_number = PhaseContent.objects.filter(phase__position_id=rec.get('position')).count()
            # 统计已经完成的阶段任务和
            completed_number = RecordDetail.objects.filter(record__trainee__eid=rec.get('eid'),
                                                           record__trainee__position_id=rec.get('position'),
                                                           status_id__in=[2]).count()
            # 修改状态
            if total_phase_number == completed_number and obj_trainee.status_id == 5:
                obj_trainee.status_id = 6
                obj_trainee.save()
        except Exception as e:
            return JsonResponse({'status': False, 'error': "提交培训信息出现异常，具体原因：" + str(e)})

        return JsonResponse({'status': True})


@csrf_exempt
def edit_record_commit(request):
    """用户记录状态修改的提交"""
    # 接收前台传递的数据
    rec = request.POST
    # 获取当前操作的trainee对象
    obj_trainee = Trainee.objects.filter(eid=rec.get('eid'), position_id=rec.get('position')).first()
    # 获取当前操作的Record对象
    obj_record = Record.objects.filter(trainee=obj_trainee, phase_id=rec.get('phase')).first()
    # 获取当前操作的RecordDetail记录
    obj_recorddetail = RecordDetail.objects.filter(record=obj_record, phasecontent_id=rec.get('phasecontent')).first()
    try:
        # === 任务1： 修改RecordDetail信息=====
        obj_recorddetail.training_time = obj_recorddetail.training_time + float(rec.get('training_time'))
        obj_recorddetail.working_time = obj_recorddetail.working_time + float(rec.get('working_time'))
        obj_recorddetail.remark = obj_recorddetail.remark + "【" + datetime.now().strftime(
            "%Y-%m-%d %H:%M:%S") + "】--状态：" \
                                   "" + RecordStatus.objects.filter(id=rec.get('status')).first().name + "&nbsp&nbsp" \
                                                                                                         "工时：" + str(
            rec.get('training_time')) + "&nbsp&nbsp培训时长：" + str(rec.get('working_time')) + "&nbsp&nbsp标注：" + rec.get(
            'remark') + "<br>"
        obj_recorddetail.status_id = rec.get('status')
        obj_recorddetail.save()

        # === 任务2: 修改Record信息 ====
        obj_record.total_working = obj_record.total_working + float(rec.get('working_time'))
        obj_record.total_training = obj_record.total_training + float(rec.get('training_time'))
        if rec.get('status') == "2":
            obj_record.pass_task += 1
            obj_record.fail_task -= 1
        obj_record.save()

        # == 任务03：修改Trainee信息 =====
        # 思路：当前职位的phasecontent内容数 和 recorddetail中状态为pass数量如果一样，表明已经完成！
        total_number = PhaseContent.objects.filter(phase__position_id=rec.get('position')).count()
        complete_number = RecordDetail.objects.filter(record__trainee__eid=rec.get('eid'),
                                                      record__trainee__position_id=rec.get('position'),
                                                      status_id__in=[2]).count()
        if total_number == complete_number and obj_trainee.status_id == 5:
            obj_trainee.status_id = 6
            obj_trainee.save()

        # ==== 返回 ===
        return JsonResponse({'status': True, })
    except Exception as e:
        return JsonResponse({'status': False, 'error': "修改内容状态出现异常，具体原因：" + str(e)})


def get_phase_fail_content(request):
    """获取当前阶段的Fail内容"""
    # 接收前台传递的参数
    employee_id = request.POST.get('employee_id')
    position_id = request.POST.get('position_id')
    phase_name = request.POST.get('phase_name')
    # 获取当前阶段下所有Fail内容
    fail_contents = list(
        RecordDetail.objects.filter(record__trainee__eid=employee_id, record__trainee__position_id=position_id,
                                    record__phase__phasename__name=phase_name, status_id__in=[3]).values(
            'phasecontent_id', 'phasecontent__name'))
    # 返回
    return JsonResponse({'data': fail_contents})


def get_position_fail_phase(request):
    """获取某一个职位下哪些阶段有Fail内容"""
    # 获取传递的值
    employee_id = request.POST.get('employee_id')
    position_id = request.POST.get('position_id')
    # 获取当前trainee对应的record
    obj_records = list(Record.objects.filter(trainee__eid=employee_id, trainee__position_id=position_id, fail_task__gt=0
                                             ).values('phase_id', 'phase__phasename__name'))
    # 如果返回的值为null
    if not obj_records:
        return JsonResponse({'status': False, 'error': "当前职位录入的Record目前没有Fail内容！"})

    # 有fail
    data = []
    # 遍历
    for index, value in enumerate(obj_records):
        data.append({'name': value.get('phase__phasename__name'), 'value': value.get('phase_id')})
    # 返回
    return JsonResponse({'status': True, 'data': data})


def get_fail_content_by_phase(request):
    """通过阶段编号获取当前阶段下有哪些Fail内容，提供给xmselect展示"""
    # 接收前台传递的参数
    employee_id = request.POST.get('employee_id')
    position_id = request.POST.get('position_id')
    phase_id = request.POST.get('phase_id')
    # 获取当前阶段内容下fail值
    obj_details = list(
        RecordDetail.objects.filter(record__trainee__position_id=position_id, record__trainee__eid=employee_id,
                                    record__phase_id=phase_id, status_id__in=[3]).values('phasecontent_id',
                                                                                         'phasecontent__name'))
    # 定义集合
    data = []
    # 遍历
    for index, value in enumerate(obj_details):
        data.append({'name': value.get('phasecontent__name'), 'value': value.get('phasecontent_id')})
    # 返回
    return JsonResponse({'data': data})


def position_cert(request):
    """职位的认证"""
    # 接受前端传递的值
    eid = request.POST.get('certEid')
    position_id = request.POST.get('certPositionId')
    cert_result = request.POST.get('certResult')
    # 获取Trainee对象
    obj_trainee = Trainee.objects.filter(eid=eid, position_id=position_id).first()
    # 如果是选择的是认证成功！
    if cert_result == '7':
        # 判断当前职位是否都pass
        if obj_trainee.status_id !=6:
            return JsonResponse({'status': False, 'error': '当前职位目前不是处于待认证状态，无法完成认证！'})
    elif cert_result =='8':
        # 判断当前所有的内容是否完成！
        total_number = PhaseContent.objects.filter(phase__position_id=position_id).count()
        complete_number = RecordDetail.objects.filter(record__trainee=obj_trainee, status_id__in=[2,3]).count()
        # 判断是否一样
        if total_number != complete_number:
            return JsonResponse({'status': False, 'error': '当前职位的内容没有全部完成，无法完成认证！'})

    # === 开始认证 ===
    try:
        # 修改状态： 7--认证成功    8-- 认证失败
        obj_trainee.status_id = cert_result
        obj_trainee.save()
        return JsonResponse({'status': True})
    except Exception as e:
        return JsonResponse({'status': False, 'error': '职位认证出现异常！具体原因：' + str(e)})